/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param head The linked list's head.
 Note that the head is guaranteed to be not null, so it contains at least one node.
 * @param {ListNode} head
 */
var Solution = function (head) {
    this.head = head;
};

/**
 * Returns a random node's value.
 * @return {number}
 */
Solution.prototype.getRandom = function () {
    let i = 0, res = 0;
    let p = this.head;

    // while循环遍历链表
    while (p != null) {
        // 生成一个 [0, i) 之间的整数
        // 这个整数等于 0 的概率就是 1/i
        if (Math.floor(Math.random() * (++i)) === 0) {
            res = p.val;
        }
        p = p.next;
    }
    return res;
};


/**
 * Your Solution object will be instantiated and called as such:
 * var obj = new Solution(head)
 * var param_1 = obj.getRandom()
 */


/**
 * @param {number[]} nums
 */
var Solution = function (nums) {
    this.nums = nums;
    // 需要k个数据，在本题中，k等于1
    this.need = 1;
};

/**
 * @param {number} target
 * @return {number}
 */
// 假设当前正要读取第n个数据，则我们以1/n的概率留下该数据，否则以(n-1)/n 的概率留下前n-1个数据中的一个。
// 而前n-1个数组留下的那个概率为1/(n-1),
// 因此最终留下上次n-1个数中留下的那个数的概率为[1/(n-1)]*[(n-1)/n] = 1/n,符合均匀分布的要求
//

Solution.prototype.pick = function (target) {
    let count = 0
    let res = 0

    this.nums.forEach((value, key) => {
        if (value === target) {
            //我们的目标对象中选取。
            count++;
            //我们以1/n的概率留下该数据
            if (Math.floor(Math.random() * count) === 0) {
                res = key;
            }
        }
    })
    return res
};

/**
 * Your Solution object will be instantiated and called as such:
 * var obj = new Solution(nums)
 * var param_1 = obj.pick(target)
 */